package com.sentrix.auto.printercenter.application;

import com.mybatisflex.core.paginate.Page;
import com.sentrix.auto.printercenter.domain.entity.PrinterTaskEntity;
import com.sentrix.auto.printercenter.domain.entity.StationEntity;
import com.sentrix.auto.printercenter.infrastructure.persistence.IStationRepository;
import com.sentrix.auto.printercenter.presentation.center.dto.StationAddReqDto;
import com.sentrix.auto.printercenter.presentation.center.dto.StationPageQueryReqDto;
import com.sentrix.auto.printercenter.presentation.center.dto.StationResDto;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;

@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class StationService {
    @Resource
    private IStationRepository stationRepository;

    public void addOrEdit(StationAddReqDto stationAdd) {
        StationEntity stationEntity = stationRepository.findByCode(stationAdd.getCode());
        if(Objects.isNull(stationEntity)){
            stationEntity = new StationEntity();
        }
        updateStationEntity(stationEntity, stationAdd);
        stationRepository.saveOrUpdate(stationEntity);
    }

    /**
     * 更新站点实体的公共方法
     * @param stationEntity 站点实体
     * @param stationAdd 站点添加请求DTO
     */
    private void updateStationEntity(StationEntity stationEntity, StationAddReqDto stationAdd) {
        if (StringUtils.isNotBlank(stationAdd.getCode())) {
            stationEntity.setCode(stationAdd.getCode());
        }
        if (StringUtils.isNotBlank(stationAdd.getName())) {
            stationEntity.setName(stationAdd.getName());
        }
        if (Objects.nonNull(stationAdd.getPrinterCodes())) {
            stationEntity.setPrinterCodes(stationAdd.getPrinterCodes());
        }
    }

    public void remove(String stationCode) {
        stationRepository.removeByCode(stationCode);
    }

    public <R> R findByCode(String stationCode, Function<StationEntity, R> convertFun) {
        StationEntity stationEntity = stationRepository.findByCode(stationCode);
        return Objects.nonNull(stationEntity) ? convertFun.apply(stationEntity) : null;
    }

    public List<StationResDto> listAll() {
        return stationRepository.list().stream().map(StationResDto::fromDomain).toList();
    }

    public <R> Page<R> page(StationPageQueryReqDto param, Function<StationEntity, R> convert) {
        Page<StationEntity> page = stationRepository.pageQuery(param.getPageParam().getCurrentPage(), param.getPageParam().getPageSize(), param.getCode(),param.getName(), param.getPrinterCodes());
        return page.map(convert);
    }
}
